package org.example.cake.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Param;
import org.example.cake.common.Rep;
import org.example.cake.common.Repsecond;
import org.example.cake.entity.Category;
import org.example.cake.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;


@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 前端查询所有分类数据
     * @author 李丽君
     * @date 2025-07-25
     * @return 统一响应格式
     */
    @GetMapping("/getCategoryListFront")
    public Rep getCategoryListFront() {
        List<Category> categoryList = categoryService.getCategoryList();
        return new Rep().addData("categoryList", categoryList);
    }


    /**
     * 查询所有分类数据
     * @author 罗江锦
     * @return 所有分类数据
     */
    @GetMapping("/selectAllCategory")
    public Rep selectAllCategory(
            @RequestParam(defaultValue = "page") Integer page,
            @RequestParam(defaultValue = "pageSize") Integer pageSize) {

        // 必须在使用查询前调用startPage
        PageHelper.startPage(page, pageSize);
        List<Category> listCategory = this.categoryService.selectAllCategory();

        // 使用PageInfo包装结果
        PageInfo<Category> pageInfo = new PageInfo<>(listCategory);

        return new Rep()
                .addData("listCategory", pageInfo.getList())
                .addData("total", pageInfo.getTotal())
                .addData("pageNum", pageInfo.getPageNum())
                .addData("pageSize", pageInfo.getPageSize());
    }

    /**
     * 根据分类名字查询分类
     * @author 罗江锦
     * @param categoryName 分类名称
     * @return 分类集合列表
     */
    @GetMapping("/seCaByCaName")
    public Rep selectCategorysByCategoryName(@Param("page") Integer page, @Param("pageSize") Integer pageSize
            , @Param("categoryName") String categoryName){
        // 开启分页
        PageHelper.startPage(page,pageSize);
        // 执行查询
        List<Category> categoryList = categoryService.selectCategorysByCategoryName(categoryName);
        // 创建分页对象
        PageInfo<Category> categoryPageInfo=new PageInfo<>(categoryList);
        // 返回
        return new Rep().addData("snacksPageInfo", categoryPageInfo);
    }

    /**
     * 根据分类内容模糊查询分类
     * @author 罗江锦
     * @param categoryDesc 分类名称
     * @return 分类集合列表
     * 测试上传
     */
    @GetMapping("/seCaByCadesc")
    public Rep selectCategorysByCategorydesc(@Param("page") Integer page, @Param("pageSize") Integer pageSize
            , @Param("categoryDesc") String categoryDesc){
        // 开启分页
        PageHelper.startPage(page,pageSize);
        // 执行查询
        List<Category> categoryList = categoryService.selectCategorysByCategorydesc(categoryDesc);
        // 创建分页对象
        PageInfo<Category> categoryPageInfo=new PageInfo<>(categoryList);
        // 返回
        return new Rep().addData("snacksPageInfo", categoryPageInfo);
    }

    /**
     * 新添分类
     * @author 罗江锦
     * @param category 分类实体
     * @return 受影响的行数
     */
    @PostMapping("/insertCategory")
    public Rep insertCategory(@RequestBody Category category) {
        Rep rep = new Rep();

        try {
            // 验证必填字段
            if (category.getCategoryname() == null || category.getCategoryname().trim().isEmpty()) {
                rep.setCode(400);
                rep.setMsgerr("分类名称不能为空");
                return rep;
            }

            if (category.getCategoryicon() == null || category.getCategoryicon().trim().isEmpty()) {
                rep.setCode(400);
                rep.setMsgerr("请上传分类图标");
                return rep;
            }

            System.out.println("接收到的分类数据: " + category);

            int result = categoryService.insertCategory(category);
            if (result > 0) {
                rep.setCode(200);
                rep.setMsgerr("添加分类成功");
                rep.addData("categoryId", category.getCategoryid());
            } else {
                rep.setCode(500);
                rep.setMsgerr("添加分类失败");
            }
        } catch (Exception e) {
            rep.setCode(500);
            rep.setMsgerr("添加分类时出错: " + e.getMessage());
        }

        return rep;
    }

    /**
     * 修改分类
     * @author 罗江锦
     * @param category 分类实体
     * @return 受影响的行数
     */
    @PostMapping("/updateCategoryend")
    public Rep updateCategoryend(@RequestBody Category category) {
        Rep rep = new Rep(); // 初始化统一响应对象
        try {
            // 验证必填参数
            if (category.getCategoryid() == null) {
                rep.setCode(400);
                rep.setMsgerr("分类ID不能为空");
                return rep;
            }
            if (category.getCategoryname() == null || category.getCategoryname().trim().isEmpty()) {
                rep.setCode(400);
                rep.setMsgerr("分类名称不能为空");
                return rep;
            }

            // 执行更新操作
            int result = categoryService.updateCategory(category);
            if (result > 0) {
                rep.setCode(200); // 成功状态码
                rep.setMsgerr("修改成功");
            } else {
                rep.setCode(500); // 失败状态码
                rep.setMsgerr("修改失败，分类不存在或未修改内容");
            }
        } catch (Exception e) {
            rep.setCode(500);
            rep.setMsgerr("修改失败: " + e.getMessage());
        }
        return rep;
    }

    /**
     * 删除分类
     *@author 罗江锦
     * @param categoryid 分类编号
     * @return 受影响的行数
     */
    @GetMapping("/deleteCategory")
    public String delCategory(@Param("categoryid") Integer categoryid){
        int deleteCategory = categoryService.delCategory(categoryid);
        if (deleteCategory>0){
            return "Delete Success";
        }else {
            return "Delete Fail";
        }
    }


    /**
     * 查询所有分类数据
     * @return 统一响应格式
     */
    @GetMapping("/getCategoryList")
    public Repsecond getCategoryList() {
        try {
            List<Category> categoryList = categoryService.getCategoryList();
            return new Repsecond()
                    .addData("categoryList", categoryList)
                    .addData("count", categoryList.size());
        } catch (Exception e) {
            return new Repsecond()
                    .setCode(500)
                    .setMsgerr("查询分类列表失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取分类详情
     * @param categoryId 分类ID
     * @return 统一响应格式
     */
    @GetMapping(value = "/{categoryId}", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Category> getCategoryById(@PathVariable Integer categoryId) {
        Category category = categoryService.selectByPrimaryKey(categoryId);
        if (category == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(category);
    }

    /**
     * 新增分类
     * @param category 分类实体
     * @return 统一响应格式
     */
    @PostMapping("/addCategory")
    public Repsecond addCategory(@RequestBody Category category) {
        try {
            if (category.getCategoryname() == null || category.getCategoryname().isEmpty()) {
                return new Repsecond()
                        .setCode(400)
                        .setMsgerr("分类名称不能为空");
            }

            int result = categoryService.insertSelective(category);
            if (result > 0) {
                return new Repsecond()
                        .setMsgerr("添加成功")
                        .addData("categoryId", category.getCategoryid());
            }
            return new Repsecond()
                    .setCode(500)
                    .setMsgerr("添加失败");
        } catch (Exception e) {
            return new Repsecond()
                    .setCode(500)
                    .setMsgerr("添加分类失败: " + e.getMessage());
        }
    }

    /**
     * 更新分类信息
     * @param category 分类实体
     * @return 统一响应格式
     */
    @PostMapping("/updateCategory")
    public Repsecond updateCategory(@RequestBody Category category) {
        try {
            if (category.getCategoryid() == null) {
                return new Repsecond()
                        .setCode(400)
                        .setMsgerr("分类ID不能为空");
            }

            int result = categoryService.updateByPrimaryKeySelective(category);
            if (result > 0) {
                return new Repsecond()
                        .setMsgerr("更新成功");
            }
            return new Repsecond()
                    .setCode(500)
                    .setMsgerr("更新失败");
        } catch (Exception e) {
            return new Repsecond()
                    .setCode(500)
                    .setMsgerr("更新分类失败: " + e.getMessage());
        }
    }

    /**
     * 删除分类
     * @param categoryId 分类ID
     * @return 统一响应格式
     */
    @DeleteMapping("/{categoryId}")
    public ResponseEntity<Map<String, Object>> deleteCategory(
            @PathVariable Integer categoryId) {

        // 1. 参数验证
        if (categoryId == null || categoryId <= 0) {
            return ResponseEntity.badRequest().body(Map.of(
                    "code", 400,
                    "message", "分类ID必须为正整数"
            ));
        }

        // 3. 执行业务逻辑
        try {
            categoryService.deleteByPrimaryKey(categoryId);
            return ResponseEntity.ok(Map.of(
                    "code", 200,
                    "message", "删除成功"
            ));
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Map.of(
                    "code", 500,
                    "message", "删除失败: " + e.getMessage()
            ));
        }
    }

    /**
     * 批量删除分类
     * @param ids 分类ID列表
     * @return 统一响应格式
     */
    @DeleteMapping("/batch")
    public Repsecond batchDeleteCategory(@RequestBody List<Integer> ids) {
        try {
            if (ids == null || ids.isEmpty()) {
                return new Repsecond()
                        .setCode(400)
                        .setMsgerr("参数不能为空");
            }

            int successCount = 0;
            for (Integer id : ids) {
                successCount += categoryService.deleteByPrimaryKey(id);
            }

            return new Repsecond()
                    .setMsgerr("批量删除完成")
                    .addData("successCount", successCount)
                    .addData("totalCount", ids.size());
        } catch (Exception e) {
            return new Repsecond()
                    .setCode(500)
                    .setMsgerr("批量删除失败: " + e.getMessage());
        }
    }

    /**
     * 上传分类图标
     * @param file 图片文件
     * @return 统一响应格式
     */
    @PostMapping("/uploadIcon")
    public Repsecond uploadIcon(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return new Repsecond()
                        .setCode(400)
                        .setMsgerr("文件不能为空");
            }
            return new Repsecond()
                    .setMsgerr("上传成功");
        } catch (Exception e) {
            return new Repsecond()
                    .setCode(500)
                    .setMsgerr("上传失败: " + e.getMessage());
        }
    }

}
